﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;
using System.Threading;


namespace server
{
    public partial class Form1 : Form
    {
        String ip;
        int port;
        Socket serverlistensocket=null;
        Thread serverThread;
        //Socket clientlistensocket;
        Socket clientsocket;
        public Form1()
        {
            InitializeComponent();
            startserver.Text = "启动服务器";
            stopserver.Text =  "停止服务器";
            IPaddress.Text = "服务器端的IP地址：";
            Port.Text = "监听端口";
            IPtextBox.Text = BaseClass.GetIP();
            PorttextBox.Text = "1234";
            lstServer.Items.Add("服务器端信息显示：");
            //BaseClass baseclass = new BaseClass();

            
        }





       private void ServerStart()
        {
            ip = IPtextBox.Text;
            port = Convert.ToInt16(PorttextBox.Text);

            IPAddress IP = IPAddress.Parse(ip);
            IPEndPoint IPE = new IPEndPoint(IP, port);
            

            //MessageBox.Show("启动监听");
          //  try
            {
                serverlistensocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                serverlistensocket.Bind(IPE);
                serverlistensocket.Listen(10);
                lstServer.Items.Add("启动服务器端的监听，等待客户端连接");
            }

            while (true)
            {
                try
                {
                    clientsocket = serverlistensocket.Accept();
                    
                    Thread clientThread = new Thread(new ThreadStart(ReceiveData));
                    //MessageBox.Show("成功启动一个新监听进程");
                    clientThread.Start();
                    
                }
                catch (Exception ex)
                {
                    MessageBox.Show("listening error:" + ex.Message);
                }
                
            }                  

            
        }
       



        private void stopserver_Click(object sender, EventArgs e)
        {
            if(clientsocket!=null)
                //clientsocket.Shutdown(SocketShutdown.Send);

            if(serverlistensocket!=null)
            //serverlistensocket.Shutdown(SocketShutdown.Receive);

            clientsocket.Close();
           // serverlistensocket.Close();
            Application.Exit();
        }

        private void ReceiveData()
        {
            bool keepalive = true;
            Socket s = clientsocket;
            Byte[] buffer = new Byte[1024];


            //根据收听到的客户端套接字向客户端发送信息
            IPEndPoint clientep = (IPEndPoint)s.RemoteEndPoint;
            lstServer.Items.Add("Client：" + clientep.Address + "(" + clientep.Port + ")");

            string welcome = "客户端已经和服务器端建立连接 ";
            lstServer.Items.Add("客户端已经和服务器端建立连接");

            byte[] data = new byte[1024];
            data = Encoding.Unicode.GetBytes(welcome);
            s.Send(data, data.Length, SocketFlags.None);



            while (keepalive)
            {
                //在套接字上接收客户端发送的信息
                int bufLen = 0;
                try
                {
                    bufLen = s.Available;

                    s.Receive(buffer, 0, bufLen, SocketFlags.None);
                    if (bufLen == 0)
                        continue;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("接收错误:" + ex.Message);
                    return;
                }
                clientep = (IPEndPoint)s.RemoteEndPoint;
                string clientcommand = System.Text.Encoding.ASCII.GetString(buffer).Substring(0, bufLen);

                lstServer.Items.Add(clientcommand + "(" + clientep.Address + ":" + clientep.Port + ")");
            }



        }

        private void startserver_Click(object sender, EventArgs e)
        {
            serverThread = new Thread(new ThreadStart(ServerStart));
            serverThread.Start();
            lstServer.Items.Add("服务器端开始监听 .....");

        }
    }
}